use super::{err, err_value, throw_err, Bytes, ConTcp, Connect, ECode, VBase, Value, VecV};

pub fn get_connect(id: &str, client: &Connect) -> Result<ConTcp, Value> {
    match client.get(id) {
        Some(v) => Ok(v.clone()),
        None => {
            throw_err!(ECode::Connect, "Connect PLC error");
        }
    }
}

pub fn write_bool(c: i64, val: &VecV) -> Result<Vec<bool>, Value> {
    let mut iter = val.iter();

    if c > 0 {
        let mut ret = Vec::new();

        for it in iter {
            let v = it.ckbool()?;
            ret.push(v);
        }

        ret.truncate(c as usize);

        return Ok(ret);
    }

    if let Some(it) = iter.next() {
        let v = it.ckbool()?;
        return Ok(vec![v]);
    }

    err!(ECode::EmptyData, "no data")
}

pub fn write_val(c: i64, val: &VecV) -> Result<Vec<i64>, Value> {
    let mut iter = val.iter();

    if c > 0 {
        let mut ret = Vec::new();

        for it in iter {
            let v = it.cki64()?;
            ret.push(v);
        }

        ret.truncate(c as usize);

        return Ok(ret);
    }

    if let Some(it) = iter.next() {
        let v = it.cki64()?;
        return Ok(vec![v]);
    }

    err!(ECode::EmptyData, "no data")
}

pub fn write_str(c: i64, val: &VecV) -> Result<Vec<Bytes>, Value> {
    let mut iter = val.iter();

    if c > 0 {
        let mut ret = Vec::new();

        for it in iter {
            let it = it.ckstr()?.to_string();
            let v = Bytes::from(it);
            ret.push(v);
        }

        ret.truncate(c as usize);

        return Ok(ret);
    }

    if let Some(it) = iter.next() {
        let it = it.ckstr()?.to_string();
        let v = Bytes::from(it);
        return Ok(vec![v]);
    }

    err!(ECode::EmptyData, "no data")
}

pub fn write_float(c: i64, val: &VecV) -> Result<Vec<f64>, Value> {
    let mut iter = val.iter();

    if c > 0 {
        let mut ret = Vec::new();

        for it in iter {
            let v = it.ckf64()?;
            ret.push(v);
        }

        ret.truncate(c as usize);

        return Ok(ret);
    }

    if let Some(it) = iter.next() {
        let v = it.ckf64()?;
        return Ok(vec![v]);
    }

    err!(ECode::EmptyData, "no data")
}
